package com.inspur_video.inspur_video.service;

import com.aliyuncs.vod.model.v20170321.*;
import com.inspur_video.inspur_video.aliyun.ALiYunUtil;
import com.inspur_video.inspur_video.bean.History;
import com.inspur_video.inspur_video.bean.tofront.MainPageInfo;
import com.inspur_video.inspur_video.bean.video.*;
import com.inspur_video.inspur_video.dao.HistoryDao;
import com.inspur_video.inspur_video.dao.VideoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 小浩
 * @date 2018-07-30 11:22
 * @package com.inspur_video.inspur_video.service
 * @description
 */
@Service
@Transactional
public class VideoService {
    @Autowired
    VideoDao videoDao;
    @Autowired
    HistoryDao historyDao;

    /**
     * 根据数据库主键查询视频信息
     *
     * @param id
     * @return
     */
    public Video getVideoInfo(int id) {
        return videoDao.findVideoByVId(id);
    }


    /**
     * 根据阿里云主键数据库主键查询视频信息
     *
     * @param id
     * @return
     */
    public Video getVideoInfoByAId(String id) {
        return videoDao.findVideosByAIdEquals(id);
    }

    /**
     * 根据阿里云主键查询视频信息
     *
     * @param aId 视频ID，前端传入
     * @return
     */
    public VideoPlay getALiVideoInfo(String aId) {
        GetVideoInfoResponse response = new GetVideoInfoResponse();
        VideoPlay<GetVideoInfoResponse.Video> video = new VideoPlay();
        video.setAId(aId);
        try {
            response = ALiYunUtil.getVideoInfo(aId);
            video.setAVideo(response.getVideo());
        } catch (Exception e) {
            return null;
        }
        return video;
    }

    /**
     * 获取播放地址相关bean，不走授权
     *
     * @param aId
     * @param uId
     * @return
     */
    public List<GetPlayInfoResponse.PlayInfo> getALiVideoPlay(String definition, String aId, int uId) {
        GetPlayInfoResponse playInfoResponse = new GetPlayInfoResponse();
        try {
            playInfoResponse = ALiYunUtil.getPlayByDefinitionAndId(definition, aId);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = playInfoResponse.getPlayInfoList();
            Video findvideo = videoDao.findVideosByAIdEquals(aId);
            if (uId != 0) {
                saveHistoryInfo(findvideo, aId, uId);
            }
            return playInfoList;
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
            return null;
        }
    }

    private void saveHistoryInfo(Video findvideo, String aId, int uId) {
        History history = new History();
        history.setUId(uId);
        history.setCoverURL(findvideo.getCoverURL());
        history.setVDescribe(findvideo.getVDescribe());
        history.setVTitle(findvideo.getVTitle());
        history.setVPermission(findvideo.getVPermission());
        history.setWatchTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        history.setVCategory(findvideo.getVCategory());
        history.setVNumber(findvideo.getVNumber());
        history.setVId(aId);
        history.setVTag(findvideo.getVTag());
        history.setVTotal(findvideo.getVTotal());
        /**
         * 判断数据库中的URL是否为空
         */
//            String URL = findvideo.getVURL();
//            if (URL != null) {
//                history.setVURL(findvideo.getVURL());
//            } else {
//                Map map = new HashMap();
//                for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
//                    map.put(playInfo.getDefinition(), playInfo.getPlayURL());
//                }
//                JSONObject jsonObject = new JSONObject(map);
//                findvideo.setVURL(jsonObject.toString());
//                Video video = videoDao.save(findvideo);
//                history.setVURL(video.getVURL());
//            }
//            System.out.println("v_URL:" + history.getVURL());
        historyDao.save(history);
    }

    /**
     * 获取播放地址和权限
     * @param aId 视频ID，前端传入
     * @param uId 用户ID，session获取
     */
/*    public VideoPlay getALiVideoPlayWithAuth(String aId, int uId) {
        // 初始化播放地址信息bean
        GetPlayInfoResponse playInfoResponse = new GetPlayInfoResponse();
        VideoPlay<GetPlayInfoResponse.VideoBase> video = new VideoPlay();
        // 初始化视频播放凭证bean
        GetVideoPlayAuthResponse playAuthResponse = new GetVideoPlayAuthResponse();

        video.setAId(aId);
        try {
            // 通过阿里SDK获取视频播放信息与视频播放权限
            playInfoResponse = ALiYunUtil.getPlayInfo(aId);
            playAuthResponse = ALiYunUtil.getVideoPlayAuth(aId);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = playInfoResponse.getPlayInfoList();
            video.setPlayInfoList(playInfoList);
            video.setAVideo(playInfoResponse.getVideoBase());
            video.setPlayAuth(playAuthResponse.getPlayAuth());// woc，这个字符串好长！
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
            return null;
        }
        Video findvideo = videoDao.findVideosByAIdEquals(aId);
        History history = new History();
        history.setUId(uId);
        history.setAId(aId);
        history.setImageURL(findvideo.getCoverURL());
        history.setHDescribe(findvideo.getVDescribe());
        history.setHTitle(findvideo.getVTitle());
        history.setWatchTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        *//**
     * 播放记录持久化
     *//*
        historyDao.save(history);
        return video;
    }*/

    /**
     * 查询所有影片信息
     *
     * @param status 视频状态
     * @return
     */
    public VideoList getAllVideo(String status) {
        GetVideoListResponse response = new GetVideoListResponse();
        VideoList videoList = new VideoList();
        try {
            response = ALiYunUtil.getVideoList(status);
            videoList = new VideoList(response.getTotal(), response.getVideoList());
        } catch (Exception e) {
            return null;
        }
        return videoList;
    }

    /**
     * 视频上传（包括封面图片）
     */
    public VideoUpload videoUpload(int uId, String title, String description, String fileName, String tags, int number, int total,
                                   String imageExt, int category, int permission) {
        CreateUploadVideoResponse videoResponse = new CreateUploadVideoResponse();
        CreateUploadImageResponse imageResponse = new CreateUploadImageResponse();
        VideoUpload videoUpload;
        try {
            imageResponse = ALiYunUtil.createUploadImage(imageExt);
            CoverImage coverImage = new CoverImage(imageResponse.getImageId(), imageResponse.getImageURL(),
                    imageResponse.getUploadAddress(), imageResponse.getUploadAuth());
            videoResponse = ALiYunUtil.createUploadVideo(title, description, fileName, tags, coverImage.getImageURL());
            videoUpload = new VideoUpload();
            videoUpload.setAId(videoResponse.getVideoId());
            videoUpload.setUploadAddress(videoResponse.getUploadAddress());
            videoUpload.setUploadAuth(videoResponse.getUploadAuth());
            videoUpload.setCoverImage(coverImage);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
            return null;
        }
        Video video = new Video();
        video.setVTitle(title);
        video.setAId(videoUpload.getAId());
        video.setVCategory(category);
        video.setVPermission(permission);
        video.setVDescribe(description);
        video.setVTag(tags);
        video.setVNumber(number);
        video.setVTotal(total);
        video.setCoverURL(videoUpload.getCoverImage().getImageURL());
        Video save = videoDao.save(video);
        videoUpload.setVId(save.getVId());
        return videoUpload;
    }

    /*修改视频信息*/
    public boolean updateVideos(String aid, String title, String description, String tags, Integer category, Integer permission, int number, int total) {
        UpdateVideoInfoResponse response = new UpdateVideoInfoResponse();
        try {
            response = ALiYunUtil.updateVideoInfo(aid, title, description, tags);
        } catch (Exception e) {
            return false;
        }
        Video video = videoDao.findVideosByAIdEquals(aid);
        if (title != null) {
            video.setVTitle(title);
        }
        if (description != null) {
            video.setVDescribe(description);
        }
        if (tags != null) {
            video.setVTag(tags);
        }
        if (number != 0) {
            video.setVNumber(number);
        }
        if (total != 0) {
            video.setVTotal(total);
        }
        if (total != -1) {
            video.setVPermission(permission);
        }
        if (category != -1) {
            video.setVCategory(category);
        }
        videoDao.save(video);
        return true;
    }


    /**
     * 根据标题和当前集数查询电视剧
     *
     * @param title
     * @param number
     * @return
     */
    public List<Video> getTVByTitle(String title, int number) {
        if (!title.isEmpty()) {
            title = "%" + title + "%";
        }
        return videoDao.findByVTitleLikeAndVNumber(title, number);
    }


    /*删除视频信息*/
    public boolean deleteVideos(List<String> ids) {
        DeleteVideoResponse response = new DeleteVideoResponse();
        try {
            response = ALiYunUtil.deleteVideo(ids);
        } catch (Exception e) {
            return false;
        }
        videoDao.deleteVideoByAIdIn(ids);
        return true;
    }

    /*模糊查询视频信息（根据title和描述和标签）*/
    public List<Video> findByTitleAndDescribeLike(String title, String describe, String tags) {
        if (!title.isEmpty()) {
            title = "%" + title + "%";
        }
        if (!describe.isEmpty()) {
            describe = "%" + describe + "%";
        }
        if (!tags.isEmpty()) {
            tags = "%" + tags + "%";
        }
        return videoDao.findByVTitleLikeOrVDescribeLikeOrVTagLike(title, describe, tags);
    }

    /**
     * 根据标题查询所有视频
     *
     * @param title
     * @return
     */
    public List<Video> findByTitle(String title) {
        if (!title.isEmpty()) {
            title = "%" + title + "%";
        }
        return videoDao.findByVTitleLike(title);
    }


    /**
     * 根据标题查询分类视频
     *
     * @param title
     * @return
     */
    public List<Video> findByTitleCategory(String title, int category) {
        if (!title.isEmpty()) {
            title = "%" + title + "%";
        }
        return videoDao.findByVTitleLikeAndVCategory(title, category);
    }


    /**
     * 首页获取(用户界面)
     *
     * @return
     */
    public List<List<MainPageInfo.pageInfoItem>> getMainPageInfo() {
        VideoList videoList = getAllVideo("Normal");
        List<GetVideoListResponse.Video> list = videoList.getVideoList();

        List<List<MainPageInfo.pageInfoItem>> mainPageInfos = new LinkedList<>();
        for (int i = 0; i < list.size(); i = i + 2) {
            GetVideoListResponse.Video v1 = list.get(i);
            List<MainPageInfo.pageInfoItem> mps = new LinkedList<>();


            MainPageInfo mainPageInfo = new MainPageInfo();
            MainPageInfo.pageInfoItem pageInfoItem1 = mainPageInfo.new pageInfoItem(v1.getCoverURL(), v1.getTitle(), v1.getVideoId());

            mps.add(pageInfoItem1);
            if (i + 1 != list.size()) {
                GetVideoListResponse.Video v2 = list.get(i + 1);
                MainPageInfo.pageInfoItem pageInfoItem2 = mainPageInfo.new pageInfoItem(v2.getCoverURL(), v2.getTitle(), v2.getVideoId());
                mps.add(pageInfoItem2);
            }
            mainPageInfos.add(mps);
        }
        return mainPageInfos;
    }

    /**
     * 查询分页查询(全部)
     */
    public Page<Video> getVideoPage(int num, int size) {
        VideoList videoList = getAllVideo("Normal");
        List<GetVideoListResponse.Video> list = videoList.getVideoList();
        List<String> aids = new LinkedList<>();
        for (GetVideoListResponse.Video video : list) {
            aids.add(video.getVideoId());
        }
        Page<Video> pages = videoDao.findVideosByAIdIn(aids, new PageRequest(num, size, new Sort(Sort.Direction.ASC, "vCategory", "vTitle")));
        return pages;
    }

    /**
     * 查询分页查询(模糊查询)
     */
    /*模糊查询视频信息（根据title和描述和标签）*/
    public Page<Video> findByTitleAndDescribeLikePage(String title, String describe,
                                                      String tags, int num, int size) {
        if (!title.isEmpty()) {
            title = "%" + title + "%";
        }
        if (!describe.isEmpty()) {
            describe = "%" + describe + "%";
        }
        if (!tags.isEmpty()) {
            tags = "%" + tags + "%";
        }
        return videoDao.findByVTitleLikeOrVDescribeLikeOrVTagLike(title,
                describe, tags, new PageRequest(num, size, new Sort(Sort.Direction.ASC, "vCategory", "vTitle")));
    }


    //分类查询所有
    public List<List<MainPageInfo.pageInfoItem>> getMainPageInfoSelect(int select) {


        List<Video> findVideos = videoDao.findByVCategory(select);
        //保存正常的
        List<GetVideoInfoResponse.Video> selectVideos = new LinkedList<>();

        //剔除不是正常的
        for (Video video : findVideos) {
            VideoPlay<GetVideoInfoResponse.Video> videoPlay = getALiVideoInfo(video.getAId());
            selectVideos.add(videoPlay.getAVideo());
        }

        List<List<MainPageInfo.pageInfoItem>> mainPageInfos = new LinkedList<>();
        for (int i = 0; i < selectVideos.size(); i = i + 2) {
            GetVideoInfoResponse.Video video1 = selectVideos.get(i);
            List<MainPageInfo.pageInfoItem> mps = new LinkedList<>();

            MainPageInfo mainPageInfo = new MainPageInfo();
            MainPageInfo.pageInfoItem pageInfoItem1 = mainPageInfo.new pageInfoItem(video1.getCoverURL(),
                    video1.getTitle(), video1.getVideoId());

            mps.add(pageInfoItem1);
            if (i + 1 != findVideos.size()) {
                GetVideoInfoResponse.Video video2 = selectVideos.get(i + 1);
                MainPageInfo.pageInfoItem pageInfoItem2 = mainPageInfo.new pageInfoItem(video2.getCoverURL(),
                        video2.getTitle(), video2.getVideoId());
                mps.add(pageInfoItem2);
            }
            mainPageInfos.add(mps);
        }

        return mainPageInfos;
    }
}
